﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Logging;
using NPOI.HPSF;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections.Generic;
using SystemWFH.API.Application.Command.EquipmentCommand;
using SystemWFH.API.Application.Command.WorkshopCommand;
using SystemWFH.API.DTO;
using SystemWFH.Domain;

namespace SystemWFH.API.Controllers
{
    /// <summary>
    /// 设备管理--API
    /// </summary>
    [Route("api/[controller]/[action]")]
    [Authorize]
    [ApiController]
    [AllowAnonymous]
    public class EquipmentsController : ControllerBase
    {
        /// <summary>
        /// 中介者服务
        /// </summary>
        private readonly IMediator mediator;
        /// <summary>
        /// 多图片服务
        /// </summary>
        private readonly IWebHostEnvironment _webHostEnvironment;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mediator">服务</param>
        /// <param name="webHostEnvironment">图片服务</param>
        public EquipmentsController(IMediator mediator, IWebHostEnvironment webHostEnvironment)
        {
            this.mediator = mediator;
            _webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 设备管理显示+查询+分页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultAPI<PageDTO<Equipment>>> GetAsync([FromQuery] EquipmentGetAllCommand equipmentGetAll)
        {
            ResultAPI<PageDTO<Equipment>> result = new ResultAPI<PageDTO<Equipment>>();
            try
            {
                result.Data = await mediator.Send(equipmentGetAll);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 设备管理添加
        /// </summary>
        /// <param name="equipmentAdd">实体</param>
        /// <returns>返回受影响行数</returns>
        [HttpPost]
        public async Task<ResultAPI<int>> Add(EquipmentAddCommand equipmentAdd)
        {
            ResultAPI<int> result = new ResultAPI<int>();
            try
            {
                result.Data = await mediator.Send(equipmentAdd);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 设备管理批量删除
        /// </summary>
        /// <param name="equipmentDelete">编号ID</param>
        /// <returns>返回受影响行数</returns>
        [HttpPost]
        public async Task<ResultAPI<int>> Delete(EquipmentDeleteCommand equipmentDelete)
        {
            ResultAPI<int> result = new ResultAPI<int>();
            try
            {
                result.Data = await mediator.Send(equipmentDelete);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 设备管理单删除
        /// </summary>
        /// <param name="equipmentDelete">编号ID</param>
        /// <returns>返回受影响行数</returns>
        [HttpPost]
        public async Task<ResultAPI<int>> Deletes(EquipmentDeletesCommand equipmentDelete)
        {
            ResultAPI<int> result = new ResultAPI<int>();
            try
            {
                result.Data = await mediator.Send(equipmentDelete);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 设备管理反填
        /// </summary>
        /// <param name="equipmentFind"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultAPI<Equipment>> GetByIdAsync([FromQuery] EquipmentFindCommand equipmentFind)
        {
            ResultAPI<Equipment> result = new ResultAPI<Equipment>();
            try
            {
                result.Data = await mediator.Send(equipmentFind);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 设备管理状态修改
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultAPI<int>> EquipmentStateUpdate([FromQuery] EquipmentStateCommand contract)
        {
            ResultAPI<int> result = new ResultAPI<int>();
            try
            {
                result.Data = await mediator.Send(contract);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 设备管理修改
        /// </summary>
        /// <param name="updateCommand"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultAPI<int>> UpdateAsync(EquipmentUpdateCommand updateCommand)
        {
            ResultAPI<int> result = new ResultAPI<int>(); 
            try
            {
                result.Data = await mediator.Send(updateCommand);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 上传单图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public Task<ResultAPI<string>> IFileImg(IFormFile file)
        {
            ResultAPI<string> result = new ResultAPI<string>();
            try
            {
                //string fileName = file.FileName;
                //fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileName).ToLower();
                //string path = Directory.GetCurrentDirectory() + @"\wwwroot\Image\" + fileName;
                //using (FileStream fs = new FileStream(path, FileMode.Create))
                //{
                //    file.CopyTo(fs);
                //    fs.Flush();
                //}
                //string str = "/Image/" + fileName;
                //result.Data = file.FileName + str;
                string path = Directory.GetCurrentDirectory() + @"\wwwroot\Image\" + file.FileName;
                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                result.Data = file.FileName;
            }
            catch (Exception)
            {

                throw;
            }
            return Task.FromResult(result);
        }
        /// <summary>
        /// 多图片上传
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult IFileImgs(IFormFileCollection files)
        {
            foreach (var file in files)
            {
                string fileName = file.FileName;
                fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileName).ToLower();
                string path = Path.Combine(_webHostEnvironment.WebRootPath, "Image", fileName);
                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
            }
            return Ok("所有文件上传成功");
        }
        /// <summary>
        /// 导出仓库管理
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> WarehouseXlsx([FromQuery] EquipmentGetAllCommand equipmentGetAll)
        {
            try
            {
                var qoutr = await mediator.Send(equipmentGetAll);
                IWorkbook iwkb = new XSSFWorkbook();
                ISheet isheet = iwkb.CreateSheet("设备管理");
                IRow row = isheet.CreateRow(0);
                row.CreateCell(0).SetCellValue("设备ID");
                row.CreateCell(1).SetCellValue("设备名称");
                row.CreateCell(2).SetCellValue("仓库名称");
                row.CreateCell(3).SetCellValue("设备编号");
                row.CreateCell(4).SetCellValue("设备类型");
                row.CreateCell(5).SetCellValue("状态");
                row.CreateCell(6).SetCellValue("所在生产线");
                row.CreateCell(7).SetCellValue("采购日期");
                row.CreateCell(8).SetCellValue("添加人");
                row.CreateCell(9).SetCellValue("添加日期");
                row.CreateCell(10).SetCellValue("添加人");
                row.CreateCell(11).SetCellValue("添加时间");
                int count = 1;
                foreach (var item in qoutr.pageList)
                {
                    row = isheet.CreateRow(count);
                    row.CreateCell(0).SetCellValue(item.equipmentId);
                    row.CreateCell(1).SetCellValue(item.equipmentSerialNumber);
                    row.CreateCell(2).SetCellValue(item.equipmentName);
                    row.CreateCell(3).SetCellValue(item.equipmentNumbering);
                    row.CreateCell(4).SetCellValue(item.equipmentType == 1 ? "设备一" : item.equipmentType == 2 ? "设备二" : "设备三");
                    row.CreateCell(7).SetCellValue(item.equipmentState == 1 ? "正常" : "异常");
                    row.CreateCell(8).SetCellValue(item.equipmentProductionLine);
                    row.CreateCell(9).SetCellValue(item.equipmentProcurementData.ToString());
                    row.CreateCell(10).SetCellValue(item.equipmentAddPeople);
                    row.CreateCell(11).SetCellValue(item.equipmentAddData.ToString());
                    count++;
                }
                byte[] bytes;
                using (MemoryStream ms = new MemoryStream())
                {
                    iwkb.Write(ms);
                    bytes = ms.ToArray();
                }
                string serrxlsx = new FileExtensionContentTypeProvider().Mappings[".xlsx"];

                return File(bytes, serrxlsx, "设备管理.xlsx");
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}
